<template>
  <div class="result">
    <van-nav-bar
      :title="page.q + ' 的搜索结果'"
      left-arrow
      @click-left="$router.push('/search')"
      fixed
      placeholder
    >
    </van-nav-bar>

    <div ref="content" class="content" @scroll="scrollEvent" v-if="bol">
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        @load="load">
        <van-cell
          :title="item.title"
          v-for="item in list"
          :key="item.art_id"
          @click="$router.push('/article?id=' + item.art_id + '&back=' + $route.fullPath)">
        </van-cell>
      </van-list>
    </div>
  </div>
</template>
<script>
import { search } from '@/api/search'
export default {
  name: 'Result',
  data () {
    return {
      loading: false,
      finished: false,
      page: {
        page: 1,
        per_page: 10,
        q: decodeURIComponent(this.$route.query.key)
      },
      list: [],
      scrollTop: 0,
      bol: true
    }
  },
  methods: {
    async getData () {
      const res = await search(this.page)
      this.list = res.data.data.results
      console.log('搜索结果', res)
    },
    async load () {
      const res = await search(this.page)
      this.list.push(...res.data.data.results)
      this.loading = false
      this.page.page++
      if (this.list.length >= res.data.data.total_count) {
        this.finished = true
      }
    },
    scrollEvent (e) {
      this.scrollTop = e.target.scrollTop
    }
  },
  activated () {
    if (decodeURIComponent(this.$route.query.key) === this.page.q) {
      this.$refs.content.scrollTop = this.scrollTop
    } else {
      this.loading = false
      this.finished = false
      this.page = {
        page: 1,
        per_page: 10,
        q: decodeURIComponent(this.$route.query.key)
      }
      this.list = []
      this.scrollTop = 0
      this.bol = false
      this.$nextTick(() => {
        this.bol = true
      })
    }
  }
}
</script>
<style lang="less" scoped>
.content {
  position: fixed;
  top: 46px;
  bottom: 0;
  width: 100vw;
  overflow: auto;
}
</style>
